package com.rjpacket.supernews.app.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rjpacket.supernews.app.Constants;
import com.rjpacket.supernews.app.R;
import com.rjpacket.supernews.app.models.Recycle;
import com.rjpacket.supernews.app.models.RecycleCategory;
import com.rjpacket.supernews.app.task.TaskProcessor;
import com.rjpacket.supernews.app.utils.BigImageToSmall;
import com.rjpacket.supernews.app.utils.HttpTool;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2015/3/12 0012.
 */

//利用瀑布流来显示图片
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    //上下文
    private Context context;
    //存储要显示的内容的List
    private List<RecycleCategory> list;
    //存储标题和图片

    //点击事件的实例
    private View.OnClickListener listener;

    //构造方法，初始化信息
    public RecyclerViewAdapter(Context context, List<RecycleCategory> list) {
        this.context = context;
        this.list = list;
        //点击事件实例的强转
        if (context instanceof View.OnClickListener) {
            listener = (View.OnClickListener) context;
        }
    }

    //显示布局
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image_resource_show, viewGroup, false);
        view.setOnClickListener(listener);
        return new ViewHolder(view);
    }

    private ImageView imageView;

    //绑定
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {

        if (list != null) {
            RecycleCategory category = new RecycleCategory();
            category = list.get(i);
            //String url = map.get("thumbUrl");
            //String url = category.getSourceUrl();

            //RecycleTask task = new RecycleTask();
            //task.execute(url);

            //imageView = viewHolder.imageView;
            //imageView.setTag(url);
            //设置标题显示
            //String title = map.get("title");

            viewHolder.textView.setText("5");
        }
    }

    //下载缩略图的异步任务

    private class RecycleTask extends AsyncTask<String, Integer, Bitmap> {

        String url = null;

        //private String reqUrl;

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap ret = null;

            if (params != null && params.length > 0) {

                String url = params[0];

                byte[] bytes = HttpTool.get(url);

                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                ret = bitmap;
                           /* // 检查是否有缓存
                            String fileName = null;

                            reqUrl = url;

                            try {

                                // 使用MD5将网址转换为一个特定的唯一的文件名，来进行检查
                                MessageDigest md5 = MessageDigest.getInstance("MD5");

                                byte[] bytes = md5.digest(reqUrl.getBytes());

                                fileName = toHex(bytes);

                            } catch (NoSuchAlgorithmException e) {
                                e.printStackTrace();
                            }


                            // 判断本地是否存在图片，存在就直接返回Bitmap，不存在，才联网

                            Bitmap cacheBitmap = null;

                            String state = Environment.getExternalStorageState();
                            if (Environment.MEDIA_MOUNTED.equals(state)) {
                                File sdcard = Environment.getExternalStorageDirectory();

                                File folder = new File(sdcard, "MyImages");

                                File targetFile = new File(folder, fileName);

                                if (targetFile.exists()) {
                                    cacheBitmap = BitmapFactory.decodeFile(targetFile.getAbsolutePath());
                                }

                            }

                            if (cacheBitmap == null) {

                                HttpGet request = new HttpGet(url);

                                HttpClient client = new DefaultHttpClient();

                                try {
                                    HttpResponse response = client.execute(request);
                                    StatusLine statusLine = response.getStatusLine();

                                    int statusCode = statusLine.getStatusCode();

                                    if (statusCode == 200) {
                                        HttpEntity entity = response.getEntity();

                                        byte[] bytes = EntityUtils.toByteArray(entity);


                                        state = Environment.getExternalStorageState();
                                        if (Environment.MEDIA_MOUNTED.equals(state)) {
                                            File sdcard = Environment.getExternalStorageDirectory();

                                            File folder = new File(sdcard, "MyImages");

                                            File targetFile = new File(folder, fileName);

                                            // 写缓存文件，利用targetFile输出字节数组

                                            if (!targetFile.exists()) {
                                                targetFile.createNewFile();
                                            }

                                            FileOutputStream fout = new FileOutputStream(targetFile);

                                            fout.write(bytes);

                                            fout.close();

                                        }

                                        ret = (new BigImageToSmall(bytes)).getBitmapByBytes();
                                    }
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            } else {
                                ret = cacheBitmap;
                            }
                        }*/

            }
            return ret;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null) {
                //设置图片显示
                if (imageView.getTag() != null) {
                    if (url.equals(imageView.getTag())) {
                        imageView.setImageBitmap(bitmap);
                    }
                } else {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    }

    //获取到可显示的RecyclerView的长度
    @Override
    public int getItemCount() {
        return list.size();
    }

    /*private static String toHex(byte[] data) {
        String ret = "";

        StringBuilder sb = new StringBuilder();

        for (byte b : data) {

            if (b > 0 && b < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(b));
        }

        ret = sb.toString();

        return ret;
    }*/


    //内部类写的ViewHolder，减少finViewById
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.text_resource_show_recycle);
            imageView = (ImageView) itemView.findViewById(R.id.image_resource_show_recycle);
        }
    }
}
